const { body, param } = require("express-validator");
const { validateUserName, validateObjectId } = require("../utils/validate");
const { getUser } = require("../model/user");

// 登录验证
const loginRules = [
    body("username").notEmpty().withMessage("用户名不能为空"),
    body("password").notEmpty().withMessage("密码不能为空"),
    body("captcha")
        .trim()
        .notEmpty()
        .withMessage("验证码不能为空")
        .bail()
        .custom(async (value, { req }) => {
            if (value.toLowerCase() !== req.session.captcha.toLowerCase()) {
                throw new Error("验证码不正确");
            }
        }),
];

// 注册验证
const registerRules = [
    body("username")
        .trim()
        .notEmpty()
        .withMessage("用户名不能为空")
        .bail()
        .custom(async (value) => {
            if (!validateUserName(value)) {
                throw new Error("用户名不合法");
            }
            const user = await getUser({ username: value });
            console.log(user);
            if (user) {
                throw new Error("用户名已存在");
            }
        }),
    body("password")
        .trim()
        .notEmpty()
        .withMessage("密码不能为空")
        .bail()
        .custom(async (value) => {
            if (value.length < 6 || value.length > 12) {
                throw new Error("密码长度在 6-12位");
            }
        }),
    body("captcha")
        .trim()
        .notEmpty()
        .withMessage("验证码不能为空")
        .bail()
        .custom(async (value, { req }) => {
            if (value.toLowerCase() !== req.session.captcha.toLowerCase()) {
                throw new Error("验证码不正确");
            }
        }),
];

// 修改验证
const updateRules = [
    param("id")
        .trim()
        .notEmpty()
        .withMessage("用户id不能为空")
        .custom(async (value) => {
            if (!validateObjectId(value)) {
                throw new Error("用户ID不合法");
            }
        }),
    body("username")
        .optional()
        .trim()
        .custom(async (value) => {
            if (!validateUserName(value)) {
                throw new Error("用户名不合法");
            }
            const user = await getUser({ username: value });
            if (user) {
                throw new Error("用户名已存在");
            }
        }),
    body("password")
        .optional()
        .trim()
        .custom(async (value) => {
            if (value.length < 6 || value.length > 12) {
                throw new Error("密码长度在 6-12位");
            }
        }),
];

// 详情验证
const detailRules = [
    param("id")
        .trim()
        .notEmpty()
        .withMessage("用户id不能为空")
        .custom(async (value) => {
            if (!validateObjectId(value)) {
                throw new Error("用户ID不合法");
            }
        }),
];

module.exports = {
    loginRules,
    registerRules,
    updateRules,
    detailRules,
};
